package org.amphiprion.montrictracv4.task.ludotheque;

import java.util.List;

import org.amphiprion.montrictracv4.R;
import org.amphiprion.montrictracv4.db.model.Ludotheque;
import org.amphiprion.montrictracv4.db.model.LudothequeGame;
import org.amphiprion.montrictracv4.web.model.Member;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;

public class SynchronizeLudothequeTask extends AsyncTask<Ludotheque, Integer, List<LudothequeGame>> {

	private Context context;
	private Member member;
	private String memberName;
	private ProgressDialog progress;
	private SynchronizeLudothequeListener caller;

	public SynchronizeLudothequeTask(Context context, Member member, SynchronizeLudothequeListener caller) {
		this.context = context;
		this.member = member;
		if (member == null) {
			memberName = "...";
		} else {
			memberName = member.name;
		}
		this.caller = caller;
	}

	@Override
	protected List<LudothequeGame> doInBackground(Ludotheque... params) {
		if (params[0] != null) {
			memberName = params[0].name;
		}
		((Activity) context).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				progress.setTitle(memberName);
			}
		});

		WebLudothequeParser parser = new WebLudothequeParser(context, member, this, params[0]);
		List<LudothequeGame> links = parser.parse();
		return links;
	}

	@Override
	protected void onPreExecute() {
		progress = ProgressDialog.show(context, memberName, context.getString(R.string.import_games, 0), true, true, new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				cancel(true);
				caller.importEnded(false, null);
			}
		});
	}

	public void publishProgress(int gameNumber, int totalGame) {
		publishProgress(R.string.import_game_progress, gameNumber, totalGame);
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		progress.setTitle(memberName);
		progress.setMessage(context.getResources().getString(values[0], values[1], values[2]));
	}

	@Override
	protected void onPostExecute(List<LudothequeGame> result) {
		progress.cancel();

		if (!isCancelled()) {
			caller.importEnded(result != null, result);
		}
	}

	public interface SynchronizeLudothequeListener {
		void importEnded(boolean succeed, List<LudothequeGame> result);
	}
}
